<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 卡片边框 -->
      <el-card class="tree-card">
        <treeTools :tree-node="company" :is-root="true" @addDepartments="addDepartments"></treeTools>
        <hr>
        <!-- 树形结构 el-tree -->
        <el-tree :data="depDetails" default-expand-all :props="{label:'name'}">
          <!-- 作用域插槽 -->
          <template slot-scope="obj">
            <!-- 树形 部门 -->
            <treeTools
              :tree-node="obj.data"
              @getDepartments="getDepartments"
              @addDepartments="addDepartments"
              @editDepartments="editDepartments"
              @delDepartments="getDepartments"
            ></treeTools>
          </template>
        </el-tree>
      </el-card>
      <!-- 弹窗 -->
      <addDepartments
        ref="addDept"
        :show-dialog="showDialog"
        :tree-node="treeNode"
        @addDepartments="getDepartments"
        @closeDialog="showDialog=false"
      ></addDepartments>
    </div>
  </div>
</template>

<script>
// 引入组件
import treeTools from './components/tree-tools.vue'
import { getDepartments } from '@/api/departments'
import { listToTreeData } from '@/utils/index'
import addDepartments from './components/add-department.vue'
export default {
  // 注册组件
  components: { treeTools, addDepartments },
  data() {
    return {
      company: {
        name: '',
        manager: '负责人',
        id: ''
      },
      depDetails: [],
      // 控制Dialog弹框的显示隐藏
      showDialog: false,
      // treeNode节点
      treeNode: {}
    }
  },
  created() {
    // 调用封装好的函数
    this.getDepartments()
  },
  methods: {
    // 封装钩子函数里的数据 >> 所有后台返回的公司部门数据
    async getDepartments() {
      const { depts, companyName } = await getDepartments()
      this.depDetails = listToTreeData(depts, '') // 所有部门数据
      this.company.name = companyName // 公司名字
    },

    // 添加子部门
    addDepartments(treeNode) {
      this.showDialog = true
      // 接收treeNode节点并赋值
      this.treeNode = treeNode
    },

    // 查看/编辑功能
    async editDepartments(treeNode) {
      await this.$refs.addDept.getIdDepartments(treeNode.id)
      this.showDialog = true
      this.treeNode = treeNode
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
